import { Injectable, Inject } from "@nestjs/common";
import { UserDto, UpdateUserDto, SearchUserDto } from "./dto/user.dto";

import { InjectRepository } from "@nestjs/typeorm";
import { UserEntity } from "./entities/user.entity";
import { In, Like, Repository } from "typeorm";
import { ApiResponse } from "@common/utils/api-response.util";
import { BusinessCode, UserStatus } from "@common/enums/business-code.enum";
import { PaginationResponseDto } from "@common/dto/pagination-response.dto";
import { Logger } from "@nestjs/common";

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {}

  private readonly logger = new Logger(UsersService.name);

  async create(createUser: UserDto) {
    const userToCreate = {
      ...createUser,
      createId: 1,
      updateId: 1,
      createName: "admin",
      updateName: "admin",
    };
    this.logger.log("create", createUser);
    try {
      const user = await this.userRepository.findOneBy({
        username: createUser.username,
      });
      // console.log(1, user);
      if (user) {
        return ApiResponse.fail(
          BusinessCode.BAD_REQUEST,
          "用户已存在，请勿重复创建！",
        );
      }
      const result = await this.userRepository.insert(userToCreate);
      // console.log('Insert result:', result);
      return ApiResponse.success(userToCreate);
    } catch (error) {
      // console.error('Failed to create user:', error);
      return ApiResponse.fail(
        BusinessCode.INTERNAL_SERVER_ERROR,
        "用户创建失败，请稍后再试！",
      );
    }
  }

  async findAll(query: SearchUserDto) {
    // this.logger.log("findAll", page, pageSize);
    const { page, pageSize, username, status } = query;
    if (page < 1 || pageSize < 1) {
      return ApiResponse.fail(
        BusinessCode.BAD_REQUEST,
        "页码和每页数量必须大于 0",
      );
    }

    try {
      const whereConditions: any = {
        status: In([UserStatus.ACTIVE, UserStatus.DISABLED]), // 固定状态过滤
      };

      // 动态添加用户名条件（模糊匹配）
      if (username) {
        whereConditions.username = Like(`%${username}%`);
      }

      // 动态添加状态条件
      if (status !== undefined) {
        whereConditions.status = status;
      }
      // 应当过滤 status 为 0 的用户 返回 1 和 2 状态的用户
      const [users, total] = await this.userRepository.findAndCount({
        where: whereConditions,
        skip: (page - 1) * pageSize,
        take: pageSize,
      });
      const paginationData = new PaginationResponseDto(
        users,
        total,
        page,
        pageSize,
      );
      return ApiResponse.success(paginationData);
    } catch (error) {
      // console.error('Failed to find users:', error);
      return ApiResponse.fail(
        BusinessCode.INTERNAL_SERVER_ERROR,
        "用户查询失败，请稍后再试！",
      );
    }
  }

  async findOne(userId: number) {
    this.logger.log("findOne", userId);

    try {
      const oneUser: UserEntity | null = await this.userRepository.findOneBy({
        userId,
      });

      if (!oneUser) {
        // statusCode 返回 200 但 success 返回 false
        return ApiResponse.fail(
          BusinessCode.SUCCESS,
          "查询用户不存在，请核对用户信息！",
        );
      }
      return ApiResponse.success(oneUser);
    } catch (error) {
      // console.error('Failed to find user:', error);
      return ApiResponse.fail(
        BusinessCode.INTERNAL_SERVER_ERROR,
        "用户查询失败，请稍后再试！",
      );
    }
    // return userId;
  }

  async update(id: number, updateUserDto: UpdateUserDto) {
    const updateData = {
      ...updateUserDto,
      updateId: 2,
    };
    this.logger.log("update:", id, updateUserDto);
    try {
      const result = await this.userRepository.update(id, updateData);
      if (result.affected === 0) {
        return ApiResponse.fail(
          BusinessCode.INTERNAL_SERVER_ERROR,
          "用户更新失败，未修改任何记录",
        );
      }
      return ApiResponse.success(updateData);
    } catch (error) {
      // console.error('Failed to update user:', error);
      return ApiResponse.fail(
        BusinessCode.INTERNAL_SERVER_ERROR,
        "用户更新失败，请稍后再试！",
      );
    }
  }

  async remove(id: number) {
    this.logger.log("remove", id);
    try {
      const result = await this.userRepository.update(id, {
        status: 0,
        updateId: 2,
      });
      if (result.affected === 0) {
        return ApiResponse.fail(
          BusinessCode.INTERNAL_SERVER_ERROR,
          "用户删除失败，未修改任何记录",
        );
      }
      return ApiResponse.success(null, "用户删除成功");
    } catch (error) {
      // console.error('Failed to delete user:', error);
      return ApiResponse.fail(
        BusinessCode.INTERNAL_SERVER_ERROR,
        "用户删除失败，请稍后再试！",
      );
    }
  }
}
